<!-- 客户出库详情抽屉 -->
<template>
    <div class="warehouse-details">
        <el-drawer v-model="dialogVisible" title="客户详情" size="1200px" direction="rtl">
            <div class="drawer-content">
                <div class="tab-header">
                    <div class="warehouse-info">
                        <el-row :gutter="24">
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">客户级别</div>
                                    <div class="field-value">{{ props.dialogRow.level_name || '暂无客户级别' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">联系人</div>
                                    <div class="field-value">{{ props.dialogRow.username || '暂无联系人' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">联系人电话</div>
                                    <div class="field-value">{{ props.dialogRow.phone || '暂无联系人电话' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">地区</div>
                                    <div class="field-value">{{ props.dialogRow.province + props.dialogRow.city +
                                        props.dialogRow.area || '暂无地址' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">联系人邮箱</div>
                                    <div class="field-value">{{ props.dialogRow.email || '暂无联系人邮箱' }}</div>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>

                <div class="tab-container">
                    <el-tabs v-model="activeTab">
                        <el-tab-pane label="基础信息" name="basic">
                            <div class="info-section">
                                <div class="section-title">
                                    <el-icon>
                                        <ArrowDown />
                                    </el-icon>
                                    <span>基础信息</span>
                                </div>
                                <div class="info-grid">
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">客户名称：</span>
                                            <span class="value">{{ props.dialogRow.name || '暂无客户名称' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">客户级别：</span>
                                            <span class="value">{{ props.dialogRow.level_name || '暂无客户级别' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">联系人</span>
                                            <span class="value">{{ props.dialogRow.username || '暂无联系人' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">联系电话</span>
                                            <span class="value">{{ props.dialogRow.phone || '暂无联系电话' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">联系人邮箱</span>
                                            <span class="value">{{ props.dialogRow.email || '暂无联系人邮箱' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">地区</span>
                                            <span class="value">{{ props.dialogRow.province + props.dialogRow.city +
                                                props.dialogRow.area || '暂无地区' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">详细地址</span>
                                            <span class="value">{{ props.dialogRow.address || '暂无详细地址' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">负责人</span>
                                            <span class="value">{{ props.dialogRow.contact_name || '暂无负责人' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">负责人电话</span>
                                            <span class="value">{{ props.dialogRow.contact_phone || '暂无负责人电话' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">备注</span>
                                            <span class="value">{{ props.dialogRow.note || '暂无备注' }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                   
                        </el-tab-pane>

                        <el-tab-pane label="出库订单" name="outbound-orders">
                            <div class="inventory-content" style="height: 690px;">
                                <div class="inventory-layout">
                                    <div class="product-content">
                                        <!-- 搜索框 -->
                                        <div class="search-bar">
                                            <el-input v-model="pageData.keywords" placeholder="出库单号/客户名称"
                                                style="width: 250px" @input="handleSearchChange">
                                                <template #prefix>
                                                    <el-icon>
                                                        <Search />
                                                    </el-icon>
                                                </template>
                                            </el-input>
                                            <el-select v-model="pageData.status" placeholder="请选择审核状态"
                                                style="width: 250px ;margin-left: 10px;" @change="getOutboundOrderData">
                                                <el-option label="全部" value=""></el-option>
                                                <el-option label="待提交" value="0"></el-option>
                                                <el-option label="审核中" value="1"></el-option>
                                                <el-option label="审核通过" value="2"></el-option>
                                                <el-option label="审核拒绝" value="3"></el-option>
                                            </el-select>
                                        </div>

                                        <div class="outbound-list">
                                            <el-table :data="productList" border style="width: 100%;">
                                                <el-table-column label="出库单号" prop="order_no" width="160">
                                                    <template #default="scope">
                                                        <span @click="handleOutboundDetails(scope.row)"
                                                            style="color: blue; cursor: pointer;">{{ scope.row.order_no }}</span>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="出库金额（元）" prop="total_amount" />
                                                <el-table-column label="出库日期" prop="order_date" />
                                                <el-table-column label="状态" prop="status_text" width="100" align="center">
                                                    <template #default="scope">
                                                        <el-tag size="small">{{ scope.row.status_text }}</el-tag>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="交货日期" prop="delivery_date" align="center" />
                                                <el-table-column label="客户名称" prop="customer_name" align="center" />
                                                <el-table-column label="备注" prop="note" align="center" />
                                                <el-table-column label="创建人" prop="creator_name" align="center" width="120" />
                                                <el-table-column label="创建时间" prop="created_at" align="center" width="150" />
                                            </el-table>
                                        </div>
                                        <!-- 分页 -->
                                        <div class="pagination">
                                            <Pagination 
                                                v-model:current-page="pageData.page" 
                                                v-model:page-size="pageData.pageSize"
                                                :page-sizes="[10, 20, 50, 100]" 
                                                :total="total"
                                                @current-change="getOutboundOrderData"
                                                @size-change="getOutboundOrderData"
                                                layout="total, sizes, prev, pager, next, jumper" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-tab-pane>

                        <el-tab-pane label="出库退货单" name="return-orders">
                            <div class="record-content">
                                <div class="search-bar">
                                    <el-input v-model="recordSearch" placeholder="退货单号/出库单号" style="width: 300px">
                                        <template #prefix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                    <div class="filter-buttons">
                                        <span class="margin-right-10">显示:</span>
                                        <el-button :color="outboundStatusData === 'pending' ? '#172B4D' : ''"
                                            @click="handleShowOutbound('pending')"> 审核完成 </el-button>
                                        <el-button :color="outboundStatusData === 'approved' ? '#172B4D' : ''"
                                            @click="handleShowOutbound('approved')"> 审核中 </el-button>
                                    </div>
                                </div>

                                <div class="record-list outbound-list">
                                    <el-table :data="recordList" border style="width: 100%">
                                        <el-table-column label="出库退货单号" prop="recordNo" width="160">
                                            <template #default="scope">
                                                <span @click="handleOutboundReturnDetails(scope.row)"
                                                    style="color: blue; cursor: pointer;">{{ scope.row.recordNo }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="出库单号" prop="name" width="auto" />
                                        <el-table-column label="退货金额" prop="code" width="auto" />
                                        <el-table-column label="退货日期" prop="model" width="auto" />
                                        <el-table-column label="状态" prop="unit" width="auto" />
                                        <el-table-column label="付款状态" prop="stock" width="auto" />
                                        <el-table-column label="付款金额" prop="minStock" width="auto" />
                                        <el-table-column label="备注" prop="manager" width="auto" />
                                        <el-table-column label="创建人" prop="names" width="auto" />
                                        <el-table-column label="操作记录" prop="address" min-width="auto" />
                                    </el-table>
                                </div>

                                <div class="pagination">
                                    <Pagination v-model:current-page="recordPage" v-model:page-size="recordPageSize"
                                        :page-sizes="[10, 20, 50, 100]" :total="recordTotal"
                                        layout="total, sizes, prev, pager, next, jumper" />
                                </div>
                            </div>
                        </el-tab-pane>

                        <el-tab-pane label="操作记录" name="operation-records">
                            <div class="stock-check-content">
                                <div class="stock-check-list outbound-list">
                                    <el-table :data="stockCheckList" border style="width: 100%" v-loading="false">
                                        <el-table-column label="操作单号" prop="checkNo" width="180" />
                                        <el-table-column label="操作名称" prop="checkName" width="180" />
                                        <el-table-column label="操作日期" prop="date" width="140" />
                                        <el-table-column label="操作类型" prop="warehouse" width="150" />
                                        <el-table-column label="状态" prop="status" width="100">
                                            <template #default="scope">
                                                <el-tag v-if="scope.row.status == 1" type="success">已完成</el-tag>
                                                <el-tag v-if="scope.row.status == 2" type="warning">进行中</el-tag>
                                                <el-tag v-if="scope.row.status == 3" type="info">待处理</el-tag>
                                                <el-tag v-if="scope.row.status == 4" type="danger">已取消</el-tag>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="操作人" prop="productCount" width="120" align="center" />
                                        <el-table-column label="备注" prop="remark" width="auto" align="center" />
                                        <el-table-column label="创建时间" prop="creator" width="160" align="center" />
                                    </el-table>
                                </div>

                                <div class="pagination">
                                    <Pagination 
                                        v-model:current-page="stockCheckPage"
                                        v-model:page-size="stockCheckPageSize" 
                                        :page-sizes="[10, 20, 50, 100]"
                                        :total="stockCheckTotal" 
                                        @current-change="getCustomerOperationList"
                                        @size-change="getCustomerOperationList"
                                        layout="total, sizes, prev, pager, next, jumper" />
                                </div>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </el-drawer>
        <OutboundOrderDetails ref="outboundOrderDetailsRef" />
        <OutboundReturnOrderDetails ref="outboundReturnOrderDetailsRef" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ArrowDown, Search } from '@element-plus/icons-vue';
import Pagination from "@/components/Pagination.vue";
import OutboundOrderDetails from './OutboundOrderDetails.vue';//出库订单详情
import OutboundReturnOrderDetails from './OutboundReturnOrderDetails.vue';//出库退货单详情
import api from '@/api';
import { ElMessage } from 'element-plus';

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    }
});

const emit = defineEmits(['update:dialogVisible']);

const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => emit('update:dialogVisible', val)
});

const outboundOrderDetailsRef = ref<any>(null);//出库订单详情
const outboundReturnOrderDetailsRef = ref<any>(null);//出库退货单详情
const activeTab = ref('basic');

// ------------------出库订单模块--------------
const total = ref(0);
const productList = ref([]);

// 获取出库订单所需参数
const pageData = ref({
    page: 1,
    pageSize: 10,
    keywords: '',
    status: '',
});

// 搜索变化处理
const handleSearchChange = () => {
    pageData.value.page = 1;
    setTimeout(() => {
        getOutboundOrderData();
    }, 300);
};

// 监听分页参数变化
watch(() => pageData.value, () => {
    if (props.dialogRow?.id && dialogVisible.value) {
        getOutboundOrderData();
    }
}, { deep: true });

// 获取出库订单数据
const getOutboundOrderData = async() => {
    if (!props.dialogRow?.id) {
        console.log('客户ID不存在，无法获取出库订单');
        return;
    }
    
    try {
        const res = await api.Outbound.getoutboundOrderList({
            ...pageData.value,
            customer_id: props.dialogRow.id,
        });

        console.log('出库订单列表:', res);

        if (res.code == 200) {
            const processedData = res.data.data.map((item: any, index: number) => ({
                ...item,
                rowNumber: (pageData.value.page - 1) * pageData.value.pageSize + index + 1,
                total_amount: item.total_amount ? `¥${parseFloat(item.total_amount).toFixed(2)}` : '--',
                order_date: item.order_date || '--',
                delivery_date: item.delivery_date || '--',
                status_text: item.status_text || '--'
            }));
            
            productList.value = processedData;
            total.value = res.data.pager.total_records;
            console.log('处理后的出库订单数据:', productList.value);
        }
    } catch (error) {
        console.error('获取出库订单列表失败:', error);
        ElMessage.error('获取出库订单列表失败');
    }
};


// 监听客户ID变化，自动获取出库订单数据
watch(() => props.dialogRow?.id, (newId) => {
    if (newId && dialogVisible.value) {
        console.log('客户ID变化，重新获取出库订单数据:', newId);
        getOutboundOrderData();
    }
}, { immediate: true });

// 监听弹窗打开状态
watch(dialogVisible, (newVal) => {
    if (newVal && props.dialogRow?.id) {
        console.log('弹窗打开，获取出库订单数据');
        getOutboundOrderData();
    }
});

// 打开出库订单详情
const handleOutboundDetails = async (row: any) => {
    console.log('打开出库订单详情:', row);
    try {
        const res = await api.Outbound.getoutboundOrderDetails({ id: row.id });
        if (res.code == 200) {
            outboundOrderDetailsRef.value.openLoading(res.data);
        }
    } catch (error) {
        console.error('获取出库订单详情失败:', error);
        ElMessage.error('获取订单详情失败');
    }
};

// ---------------出库退货单模块--------------
const recordSearch = ref('');
const recordPage = ref(1);
const recordPageSize = ref(10);
const recordTotal = ref(0);
let outboundStatusData = ref('pending');

const recordList = ref([
    {
        recordNo: 'XS240212001',
        name: 'xs7563426451263',
        code: '234',
        model: '2023-06-01',
        unit: '审核通过',
        stock: '退款成功',
        minStock: 100,
        maxStock: 1000,
        names: "花花",
        address: "操作记录1"
    },
    {
        recordNo: 'XS240212002',
        name: 'la23654321764325',
        code: '569',
        model: '2023-06-01',
        unit: '审核中',
        stock: '回款成功',
        minStock: 1000,
        maxStock: 8000,
        names: "诺诺",
        address: "操作记录2"
    }
]);

const handleShowOutbound = (status: string) => {
    outboundStatusData.value = status;
};

// 打开出库退货单详情
const handleOutboundReturnDetails = (item: any) => {
    console.log('打开出库退货单详情:', item);
    outboundReturnOrderDetailsRef.value.openLoading(item);
};

// ---------------操作记录模块--------------
const stockCheckList = ref([]);
const stockCheckPage = ref(1);
const stockCheckPageSize = ref(10);
const stockCheckTotal = ref(0);

// 获取客户操作记录
const getCustomerOperationList = async () => {

 
        const res = await api.Outbound.getoutboundOperationList({
            id: props.dialogRow.id,
            page: stockCheckPage.value,
            page_size: stockCheckPageSize.value,
        });
        
        console.log('操作记录API返回:', res);
        
        if (res.code === 200 && res.data) {
            // 处理操作记录数据
            const operationList = res.data.map((item: any) => ({
                checkNo: item.id || '--',
                checkName: getOperationTypeName(item.operator_type),
                date: item.created_at || '--',
                warehouse: item.operator_type || '--',
                status: getOperationStatus(item.operator_type),
                productCount: item.operator_name || '--',
                remark: item.describe || '--',
                creator: item.created_at || '--',
                operatorType: item.operator_type
            }));
            
            stockCheckList.value = operationList;
            stockCheckTotal.value = res.data.pager?.total_records || operationList.length;
            
            console.log('处理后的操作记录:', stockCheckList.value);
        }
    }


// 获取操作类型名称
const getOperationTypeName = (operatorType: string) => {
    const typeMap: { [key: string]: string } = {
        'edit': '编辑操作',
        'create': '创建操作',
        'delete': '删除操作',
        'update': '更新操作',
        'view': '查看操作',
        'export': '导出操作',
        'import': '导入操作',
        'audit': '审核操作',
        'submit': '提交操作',
        'cancel': '取消操作'
    };
    return typeMap[operatorType] || operatorType || '未知操作';
};

// 获取操作状态
const getOperationStatus = (operatorType: string) => {
    // 根据操作类型返回不同状态
    switch (operatorType) {
        case 'edit':
        case 'create':
        case 'update':
        case 'audit':
            return 1; // 已完成
        case 'submit':
            return 2; // 进行中
        case 'view':
            return 3; // 待处理
        case 'delete':
        case 'cancel':
            return 4; // 已取消
        default:
            return 1; // 默认已完成
    }
};

// 监听操作记录分页变化
watch([stockCheckPage, stockCheckPageSize], () => {
    if (props.dialogRow?.id && dialogVisible.value) {
        getCustomerOperationList();
    }
});

// 监听标签页切换
watch(activeTab, (newTab) => {
    if (newTab === 'operation-records' && props.dialogRow?.id) {
        getCustomerOperationList();
    }
});

// 监听弹窗打开状态，获取操作记录
watch(() => props.dialogVisible, (newVal) => {
    if (newVal && props.dialogRow?.id) {
        console.log('弹窗打开，准备获取操作记录');
        // 如果当前在操作记录标签页，立即获取数据
        if (activeTab.value === 'operation-records') {
            getCustomerOperationList();
        }
    }
});

// 监听客户ID变化
watch(() => props.dialogRow?.id, (newId) => {
    if (newId && dialogVisible.value && activeTab.value === 'operation-records') {
        console.log('客户ID变化，重新获取操作记录:', newId);
        getCustomerOperationList();
    }
}, { immediate: true });
</script>

<style lang="scss" scoped>
.warehouse-details {
    .drawer-content {
        height: calc(100% - 60px);
        overflow-y: auto;

        .tab-header {
            padding: 10px;
            background-color: #F5F7FA;

            .warehouse-info {
                .info-field {
                    padding: 10px;
                    display: flex;
                    flex-direction: column;
                    border-radius: 4px;

                    .field-label {
                        color: #909399;
                        font-size: 13px;
                        margin-bottom: 4px;
                    }

                    .field-value {
                        color: #333;
                        font-weight: 500;
                        font-size: 14px;
                    }
                }
            }
        }

        .tab-container {
            padding: 20px;

            :deep(.el-tabs__header) {
                margin-bottom: 20px;
            }
        }

        .info-section {
            margin-bottom: 24px;

            .section-title {
                background-color: #F5F7FA;
                padding: 12px 10px;
                display: flex;
                align-items: center;
                gap: 8px;
                margin-bottom: 16px;
                font-size: 14px;
                font-weight: bold;
                color: #333;

                .el-icon {
                    font-size: 16px;
                    color: #626aef;
                }
            }

            .info-grid {
                padding: 16px;
                border-radius: 4px;

                .info-row {
                    display: flex;
                    margin-bottom: 16px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .info-col {
                        flex: 1;
                        display: flex;
                        align-items: center;

                        .label {
                            width: 80px;
                            color: #909399;
                            flex-shrink: 0;
                            margin-left: 10px;
                        }

                        .value {
                            color: #333;
                            flex: 1;
                            display: inline-block;
                            padding: 6px;
                            font-size: 14px;
                            background-color: #F5F7FA;
                        }
                    }
                }
            }
        }
    }
}

:deep(.el-drawer) {
    .el-drawer__body {
        padding: 0;
    }
}

:deep(.el-tabs__nav-wrap::after) {
    height: 1px;
}

:deep(.el-tabs__active-bar) {
    background-color: #626aef;
}

:deep(.el-tabs__item.is-active) {
    color: #626aef;
}

:deep(.el-tabs__item:hover) {
    color: #626aef;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .filter-buttons {
        margin-left: 16px;
    }
}

.outbound-list {
    margin-bottom: 16px;
}

.pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
}

:deep(.el-table) {
    --el-table-header-bg-color: #F5F7FA;

    th {
        background-color: var(--el-table-header-bg-color);
        color: #606266;
        font-weight: 500;
    }
}

:deep(.el-button) {
    &.is-plain {
        &:hover {
            color: #626aef;
            border-color: #626aef;
        }
    }
}

.inventory-layout {
    display: flex;
    height: 100%;

    .product-content {
        flex: 1;

        .search-bar {
            margin-bottom: 16px;
        }
    }
}
</style>
